<?php

class ProductsController extends Controller
{
    public $_model;

    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('view', 'index', 'special', 'all', 'new', 'search'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('admin', 'delete', 'create', 'update', 'view'),
                'users' => array('@'),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function beforeAction($action)
    {
        $this->layout = Shop::module()->layout;
        return parent::beforeAction($action);
    }

    public function actionView()
    {
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Products::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function actionCreate()
    {
        $model = new Products;

        $this->performAjaxValidation($model);

        if (isset($_POST['Products'])) {
            $model->attributes = $_POST['Products'];
            if (isset($_POST['Specifications']))
                $model->setSpecifications($_POST['Specifications']);


            if ($model->save())
                $this->redirect(array('shop/admin'));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'products-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionUpdate($id, $return = null)
    {
        $model = $this->loadModel();

        $this->performAjaxValidation($model);

        if (isset($_POST['Products'])) {
            $model->attributes = $_POST['Products'];
            if (isset($_POST['Specifications']))
                $model->setSpecifications($_POST['Specifications']);
            if (isset($_POST['Variations']))
                $model->setVariations($_POST['Variations']);

            if ($model->save())
                if ($return == 'product')
                    $this->redirect(array('products/update', 'id' => $model->product_id));
                else
                    $this->redirect(array('products/admin'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete()
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel()->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_POST['ajax']))
                $this->redirect(array('index'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        /*$dataProvider = new CActiveDataProvider('Products', array(
            'criteria'=>array(
                'condition'=>'showhome=1',
                'order' => '`order` DESC',
                //'limit' => 2 //i will fix it
            )
        ));
        //$dataProvider = Products::model()->findAll();

        $companyInfo = Company::model()->findByPk(1);
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        	'intro' => $companyInfo->intro_home
        ));*/
    	
    	$criteria = new CDbCriteria();
        $criteria->condition = "showhome=1";
        $criteria->order = '`order` DESC';
        
    	$item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $companyInfo = Company::model()->findByPk(1);
        $this->render('index', array(
            'model' => Products::model()->with('frame')->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => 12,
            'items_count' => $item_count,
            'pages' => $pages,
        	'intro' => $companyInfo->intro_home
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionSpecial()
    {
        /*$dataProvider = new CActiveDataProvider('Products', array(
            'criteria' => array(
                //'condition' => 'is_special=1'
				'condition' => 'new_price<>""'
            )
        ));

        $this->render('special', array(
            'dataProvider' => $dataProvider,
        ));*/
    	
    	$criteria = new CDbCriteria();
        $criteria->condition = "new_price <> ''";
        $criteria->order = '`order` DESC';
        
    	$item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(12);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('special', array(
            'model' => Products::model()->with('frame')->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => 12,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionNew()
    {
        /*$dataProvider = new CActiveDataProvider('Products', array(
            'criteria' => array(
                'condition' => 'created_time > DATE_ADD(CURDATE(), INTERVAL -31 DAY);',
                'order' => '`order` DESC',
            )
        ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));*/
    	$criteria = new CDbCriteria();
        $criteria->condition = "created_time > DATE_ADD(CURDATE(), INTERVAL -31 DAY)";
        $criteria->order = '`order` DESC';
        
    	$item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(12);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('index', array(
            'model' => Products::model()->with('frame')->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => 12,
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionAll()
    {
        if (Yii::app()->session['keyword']) {
            unset(Yii::app()->session['keyword']);
        }
        
        $sort = 'stock DESC, `order` DESC ';
        $sortDate = Yii::app()->request->getParam('date');
        $sortPrice = Yii::app()->request->getParam('price');

        if ($sortDate)
            $sort = 'stock DESC, created_time ' . $sortDate;
        if ($sortPrice)
            $sort = 'stock DESC, price ' . $sortPrice;

        $criteria = new CDbCriteria();
        if (!empty($_POST['keyword'])) {
            $keyword = $_POST['keyword'];
            $criteria->condition = "title LIKE :keyword";
            $criteria->params = array(':keyword' => "%$keyword%");
        }
        $criteria->order = $sort;

        $item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('all', array(
            'model' => Products::model()->with('frame')->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
            'sort' => $sort
        ));
    }

    /**
     * Lists all models special.
     */
    public function actionSearch()
    {
        if (!empty($_POST['keyword'])) {
            Yii::app()->session['keyword'] = $_POST['keyword'];
        }

        $sort = 'stock DESC, created_time desc';
        $criteria = new CDbCriteria();

        if (!empty(Yii::app()->session['keyword'])) {
            $keyword = Yii::app()->session['keyword'];
            $criteria->condition = "title LIKE :keyword OR product_code LIKE :keyword";
            $criteria->params = array(':keyword' => "%$keyword%");
        }

        $criteria->order = $sort;

        $item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('search', array(
            'model' => Products::model()->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Products('search');
        if (isset($_GET['Products']))
            $model->attributes = $_GET['Products'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }
}
